<!--  货补池明细报表-->
<template>
  <a-card :bordered='false'>
    <!-- 查询区域 -->
    <search ref='search' :config='searchConfig' @search='search' @getHeight='getHeight' />

    <!-- table区域-begin -->
    <div class='page_table'>
      <vxe-grid
        ref='xGrid'
        v-bind='vexConfig'
        :align='left'
        :border='true'
        :checkbox-config='checkboxConfig'
        :columns='columns'
        :data='dataSource'
        :height='pageHeight-seachHeight-94'
        :loading='loading'
        :resizable='true'
        :showOverflow='true'
        :toolbar-config='tableToolbar'
        size='mini'
        @checkbox-change='selectChangeEvent'
        @checkbox-all='selectChangeEvent'
      >
        <template #toolbar_buttons>
            <!-- 操作按钮区域 -->
            <div class='table-operator'>
              <a-button v-has="'report:feeProprotion'" type='primary' @click="downExportXls('tpm_fabian_statistics')">导出</a-button>
            </div>
        </template>

        <template #pager>
          <vxe-pager
            :currentPage.sync='ipagination.current'
            :layouts="['Total', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump','Sizes', 'FullJump']"
            :page-size.sync='ipagination.pageSize'
            :pageSizes='ipagination.pageSizeOptions'
            :total='ipagination.total'
            @page-change='handlePageChange'>
          </vxe-pager>
        </template>
      </vxe-grid>
    </div>
    <!-- table区域-end -->

    <salesDetailModal ref='modalForm' @ok='modalFormOk'></salesDetailModal>
  </a-card>
</template>

<script>
import { PageListMixin } from '@/mixins/PageListMixin'
import { getAction, postAction } from '@api/manage'
import salesDetailModal from '@/views/tmr/costCenter/modules/salesDetailModal'
import HpayselectCom from '@/components/cn-components/HpayselectCom'

export default {
  name: 'detailedReport',
  description: '费用池明细页面',
  mixins: [PageListMixin],
  components: {
    salesDetailModal,
    HpayselectCom
  },
  data() {
    return {
      // permflag:'cn_fee_detail_impl',
      loading: false,
      searchConfig: [
        {
          type: 'tree-select',
          name: 'typeCode',
          name1: 'typeName',
          dataType:'product_type',
          placeholder: '商品分类',
        },
        {
          type: 'date-month-double',
          name: ['startMonth','endMonth'],
          placeholder: ['开始年月','结束年月']
        },
        {
          type: 'tree-select-search',
          name: 'orgCode',
          name1:'orgCodeList',
          dataType:'org-Area',
          multiple:true,
          placeholder: '选择组织'
        },
        {
          type: 'a-select',
          name: 'orgCode1',
          name1:'costTypeList',
          mode:'multiple',
          flag:true,
          option:[],
          placeholder: '费用归类'
        },
      ],
      disableMixinCreated:true,
      columns:[],
      url: {
        list: window._CONFIG['domianTpmURL'] + '/report/tpmActFabianStatisticsReport/findFabianStatisticsReport',
        check:window._CONFIG['domianTpmURL'] + 'report/tpmActExecuteReport/examineReport',
        detail: window._CONFIG['domianTpmURL'] + '/activity/findOne',
        exportXlsUrl: window._CONFIG['domianTpmURL'] + 'budget/tpmBudgetFee/exportXls',
        closeOne: window._CONFIG['domianTpmURL'] + '/activity/closeActivity',
        deleteBatch: window._CONFIG['domianTpmURL'] + '/activity/delete'
      }
    }
  },


  mounted() {
    this.$refs.search.handleToggleSearch()
  },
  methods: {
    getCostType(){
      getAction('/cnDictionaryController/getDictByCode',{dictCode:'cost_type'}).then(res=>{
        if(res.success){
          let { result=[] } = res
          this.searchConfig[3].option = result.map(item=>{
            return {
              name:item.dictDataDesc,
              value:item.dictDataCode
            }
          })
        }else {
          this.$message.error(res.message)
        }
      })
    },
    getRowSpan(text,row,index){
      let rowSpan=1
      if(index!=0&&this.dataSource[index-1].costName==text){
        return 0
      }
      for(let i=index+1;i<this.dataSource.length;i++ ){
        if(this.dataSource[i].costName==text) {
          rowSpan++
        }
      }
      return rowSpan
    },

    handleEdit: async function (record) {
      if (this.url.detail) {
        const res = await getAction(this.url.detail, {id: record.id})
        if (res && res.result) {
          record = res.result
        }else{
          this.$message.error(res.message)
        }
      }
      this.$refs.modalForm.edit(record);
      this.$refs.modalForm.title = "编辑";
    },

    loadData(arg) {
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      var params = this.getQueryParams();//查询条件
      this.loading = true;
      let request = postAction
      var that = this
      return request(this.url.list, params).then((res) => {
        if (res.success) {
          let { head, data } = res.result
          that.getColumns(head)
          that.getData(data)

        }else{
          that.$message.warning(res.message)
        }
        that.loading = false;
      })
    },

    getColumns(head){
      let columns=[{
        title:"大区",
        fixed:'left',
        align:'left',
        minWidth:140,
        children: [
          {
            title: '月份',
            minWidth:70,
            field: 'costName',
            slots: {
              default: ({ row,rowIndex }) => {
                let vm=this
                let obj = {
                  children: row.costName,
                  attrs: {},
                };
                obj.attrs.rowSpan = vm.getRowSpan(row.costName, row, rowIndex);
                obj.attrs.colSpan = rowIndex==0?2:1;
                return obj
              }
            },
            customHeaderCell:()=>{
              return {
                style:{
                  borderRight:'none'
                }
              }
            }
          },
          {
            minWidth:70,
            field: 'type',
            customRender: (text, row, index) => {
              let vm=this
              let obj = {
                children: text,
                attrs: {},
              };
              obj.attrs.colSpan = index==0?0:1;
              return obj
            },
          }
        ]
      }]

      for(let key in head){
        let item={
          title:key.split('-')[1],
          children:[]
        }
        if(key!=='总计'){
          for (let keyOne in head[key]){
            item.children.push({
              title: keyOne,
              minWidth:80,
              field: head[key][keyOne],
            })
          }
          columns.push(item)
        }
      }

      columns.push({
          title:'总计',
        minWidth:80,
          field: '总计',
          fixed:'right',
      })

      this.columns=columns

    },
    getData(data){
      let dataSource=[]
      for (let key in data[0]){
        let keyArry = key.split('-')
        let item = { id:key,type:keyArry[1], costName:keyArry[0]}
        data.forEach(v=>{
          for (let keys in v){
           if(keys===key) {
             item=Object.assign({},item,v[keys])
           }
          }
        })
        item['总计']=data[data.length-1]['总计'][key]
        dataSource.push(item)
      }
      this.dataSource=dataSource
    },

  },
  created() {
    this.getCostType()
  },
  // beforeMount() {
  //   const draggingMap = {};
  //   this.columns.forEach((col) => {
  //     draggingMap[col.field] = col.width;
  //   });
  //   const draggingState = Vue.observable(draggingMap);
  //   const resizeableTitle = (h, props, children) => {
  //     let thDom = null;
  //     const { key, ...restProps } = props;
  //     console.log(props)
  //     let col;
  //     // 复选框筛选处理
  //     if (key === 'selection-column') {
  //       col = {};
  //     } else {
  //       col = this.columns.find((item) => {
  //         const k = item.field || item.key;
  //         return k === key;
  //       });
  //     }
  //     // 未设置宽度或者设置不可伸缩时不做伸缩处理
  //     if (!col.width || col.noStretch) {
  //       return <th {...restProps}>{children}</th>;
  //     }
  //     const onDrag = (x) => {
  //       draggingState[key] = 0;
  //       // 设置一个伸缩的最小宽度，防止页面错乱
  //       col.width = Math.max(x, col.minWidth || 30);
  //     };
  //     const onDragstop = () => {
  //       draggingState[key] = thDom.getBoundingClientRect().width;
  //     };
  //     return (
  //       <th
  //         {...restProps}
  //         v-ant-ref={(r) => (thDom = r)}
  //         width={col.width}
  //         class="resize-table-th"
  //       >
  //         {children}
  //         <vue-draggable-resizable
  //           key={col.key}
  //           class="table-draggable-handle"
  //           w={10}
  //           x={col.width||draggingState[key]}
  //           z={1}
  //           axis="x"
  //           draggable={true}
  //           resizable={false}
  //           onDragging={onDrag}
  //           onDragstop={onDragstop}
  //         />
  //       </th>
  //     );
  //   };
  //   this.components = {
  //     header: {
  //       cell: resizeableTitle,
  //     },
  //   };
  // },
  watch: {
    // pageHeight(val){
    //   // 为了避免频繁触发resize函数导致页面卡顿，使用定时器
    //   if(!this.timer){
    //     // 一旦监听到的screenWidth值改变，就将其重新赋给data里的screenWidth
    //     this.pageHeight = val
    //     this.timer = true
    //     let that = this
    //     setTimeout(function(){
    //       // 打印screenWidth变化的值
    //       console.log(that.pageHeight)
    //       that.timer = false
    //     },100)
    //   }
    // }
  },


  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  }
}
</script>


<style>
.table-row-class-name{
  padding-right:80px ;
}

</style>
<style lang='less' scoped>
@import '~@assets/less/common.less';

/deep/ .ant-pagination {
  float: right;
}
/deep/ .rowClassName{
  padding-right:80px ;
}


///deep/ .resize-table-th {
//  position: relative;
//}
///deep/ .table-draggable-handle {
//  height: 100% !important;
//  bottom: 0;
//  left: auto !important;
//  right: -5px;
//  cursor: col-resize;
//  touch-action: none;
//}

</style>